package com.czl.module_base.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewbinding.ViewBinding;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.czl.base.callback.ErrorCallback;
import com.czl.base.callback.LoadingCallback;
import com.czl.base.util.DialogHelper;
import com.czl.base.util.ToastHelper;
import com.czl.module_base.R;
import com.czl.module_base.bean.ListBean;
import com.czl.module_base.databinding.FragmentBaseBinding;
import com.czl.module_base.databinding.LayoutToolbarBinding;
import com.czl.module_base.http.HttpResponse;
import com.czl.module_base.mvp.presenter.BasePresenter;
import com.czl.module_base.mvp.presenter.InjectPresenter;
import com.czl.module_base.mvp.view.IView;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.callback.SuccessCallback;
import com.kingja.loadsir.core.Convertor;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.lxj.xpopup.core.BasePopupView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @author by xubin,
 * @date on 2022/1/25.
 * PS: Not easy to write code, please indicate.
 */
public abstract class BaseFragment1<V extends ViewBinding> extends BaseRxFragment implements IView {
    protected final String TAG = this.getClass().getSimpleName();
    protected LoadService<?> loadService;

    protected V binding;
    protected LayoutToolbarBinding mToolBinding;
    private List<BasePresenter<?, ?>> mInjectPresenters;

    private BasePopupView dialog = null;
    private View mBindView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (addToolBar()) {
            FragmentBaseBinding baseBinding = FragmentBaseBinding.inflate(getLayoutInflater(), container, false);
            init(baseBinding.layoutRoot);
            return baseBinding.getRoot();
        } else {
            init(container);
            if (useLoad()) {
                return loadService.getLoadLayout();
            }
            return mBindView;
        }
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        initPresenter();
        initData(savedInstanceState);
        reload();
    }

    protected void init(ViewGroup viewGroup) {
        View rootView = initView(getLayoutInflater(), viewGroup);
        if (rootView == null) {
            binding = getBinding(getLayoutInflater(), viewGroup);
            mBindView = binding.getRoot();
        } else {
            mBindView = rootView;
        }
        if (useLoad()) {
            LoadSir loadSir = new LoadSir.Builder()
                    .addCallback(new ErrorCallback())
                    .addCallback(new LoadingCallback())
                    .setDefaultCallback(SuccessCallback.class)
                    .build();
            loadService = loadSir.register(mBindView, (Callback.OnReloadListener) v -> reload(),
                    (Convertor<HttpResponse<?>>) response -> {
                        if (response == null || !response.isSuccess()) {
                            return ErrorCallback.class;
                        } else {
                            return SuccessCallback.class;
                        }
                    });
        }
    }

    protected boolean useLoad() {
        return true;
    }

    protected View initView(LayoutInflater layoutInflater, ViewGroup container) {
        return null;
    }

    protected void initData(Bundle savedInstanceState) {

    }

    /**
     * 获取布局
     *
     * @param layoutInflater 解析器
     * @param container      父容器
     * @return ViewBinding
     */
    protected abstract V getBinding(LayoutInflater layoutInflater, ViewGroup container);

    protected boolean addToolBar() {
        return false;
    }

    protected void reload() {
        showLoading();
    }

    private void initPresenter() {
        mInjectPresenters = new ArrayList<>();
        //获得已经申明的变量，包括私有的
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            //获取变量上面的注解类型
            InjectPresenter injectPresenter = field.getAnnotation(InjectPresenter.class);
            if (injectPresenter != null) {
                try {
                    Class<? extends BasePresenter<?, ?>> type = (Class<? extends BasePresenter<?, ?>>) field.getType();
                    BasePresenter<?, ?> mInjectPresenter = type.newInstance();
                    mInjectPresenter.onStart(this);
                    field.setAccessible(true);
                    field.set(this, mInjectPresenter);
                    mInjectPresenters.add(mInjectPresenter);
                } catch (IllegalAccessException | java.lang.InstantiationException e) {
                    e.printStackTrace();
                } catch (ClassCastException e) {
                    e.printStackTrace();
                    throw new RuntimeException("SubClass must extends Class:BasePresenter");
                }
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.e(TAG, "onDestroyView");
        if (mToolBinding != null) {
            mToolBinding.unbind();
        }
        if (binding != null) {
            if (binding instanceof ViewDataBinding) {
                ((ViewDataBinding) binding).unbind();
            }
        }
        if (mInjectPresenters != null && !mInjectPresenters.isEmpty()) {
            for (BasePresenter<?, ?> presenter : mInjectPresenters) {
                presenter.onDestroy();
            }
            mInjectPresenters.clear();
        }
        mInjectPresenters = null;
    }

    @Override
    public void showDialogLoading(String title) {
        if (TextUtils.isEmpty(title)) {
            title = "加载中";
        }
        if (dialog == null) {
            dialog = DialogHelper.INSTANCE.showLoadingDialog(requireContext(), title);
        }
    }

    @Override
    public void showLoading() {
        if (loadService != null) {
            loadService.showCallback(LoadingCallback.class);
        }
    }

    @Override
    public void hideDialogLoading() {
        if (dialog != null && dialog.isShow()) {
            dialog.dismiss();
        }
    }

    @Override
    public void showLoadSuccess() {
        if (loadService != null) {
            loadService.showSuccess();
        }
    }

    @Override
    public void showEmpty() {

    }

    @Override
    public <T> void showData(T t) {

    }

    @Override
    public <T> void showHttpResponse(HttpResponse<T> httpResponse) {

    }

    protected <T> void handleResponseData1(RecyclerView recyclerView, SmartRefreshLayout smartRefreshLayout,
                                           BaseQuickAdapter<T, ?> adapter, int page, ListBean<T> list) {

        if (recyclerView.getAdapter() == null) {
            recyclerView.setAdapter(adapter);
        }
        if (smartRefreshLayout != null) {
            smartRefreshLayout.finishRefresh();
            smartRefreshLayout.finishLoadMore();
        }

        showLoadSuccess();
        if (page == 1) {
            if (list == null || list.getList() == null || list.getList().isEmpty()) {
                adapter.removeEmptyView();
                View emptyView = View.inflate(requireContext(), R.layout.common_empty_layout, null);
                emptyView.findViewById(R.id.ll_empty).setOnClickListener(v -> {
                    if (smartRefreshLayout != null) {
                        smartRefreshLayout.autoRefresh();
                    }
                });
                adapter.setEmptyView(emptyView);
                if (smartRefreshLayout != null) {
                    smartRefreshLayout.finishRefreshWithNoMoreData();
                }
                return;
            }
            T t = list.getList().get(0);
            List<T> list1 = new ArrayList<>();
            list1.add(t);
            adapter.setList(list1);
            if (smartRefreshLayout != null) {
                smartRefreshLayout.finishLoadMoreWithNoMoreData();
            }
        } else {
            if (list != null && list.getList() != null) {
                adapter.addData(list.getList());
                if (list.getTotal() == list.getList().size() || !list.hasNextPage()) {
                    if (smartRefreshLayout != null) {
                        smartRefreshLayout.finishLoadMoreWithNoMoreData();
                    }
                }
            }
        }
    }

    @Override
    public void showError(String error) {
        if (loadService != null) {
            loadService.showCallback(ErrorCallback.class);
        }
    }

    @Override
    public void showUnKnowError(String msg, int drawable) {

    }

    protected void showToast(String msg) {
        ToastHelper.INSTANCE.showNormalToast(msg);
    }

}
